package com.lml.hydrogenexpertsystem.backend.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lml.hydrogenexpertsystem.backend.constant.UserConstant;
import com.lml.hydrogenexpertsystem.backend.exception.BusinessException;
import com.lml.hydrogenexpertsystem.backend.exception.ErrorCode;
import com.lml.hydrogenexpertsystem.backend.mapper.UserMapper;
import com.lml.hydrogenexpertsystem.backend.model.entity.User;
import com.lml.hydrogenexpertsystem.backend.model.enums.UserRoleEnum;
import com.lml.hydrogenexpertsystem.backend.model.vo.LoginUserVo;
import com.lml.hydrogenexpertsystem.backend.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 梦龙
 * @date 2025/4/18 下午8:01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public long userRegister(String account, String password, String checkPassword) {
        if (StrUtil.hasBlank(account, password, checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (account.length() < 4 || password.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码过短");
        }
        if (!password.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "两次密码不一致");
        }

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account", account);
        Long count = this.baseMapper.selectCount(userQueryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号重复");
        }

        // 密码加密
        String encryptPassword = getEncryptPassword(password);
        //插入数据到数据库中
        User user = new User();
        user.setAccount(account);
        user.setPassword(encryptPassword);
        user.setUsername("无名");
        user.setRole(UserRoleEnum.USER.getValue());
        // 主键回填
        boolean saveResult = this.save(user);
        if (!saveResult) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "注册失败");
        }
        return user.getId();
    }

    public String getEncryptPassword(String password) {
        final String SALT = "lml";
        return DigestUtils.md5DigestAsHex((SALT + password).getBytes());
    }

    @Override
    public LoginUserVo userLogin(String account, String password, HttpServletRequest request) {
        // 1.校验
        if (StrUtil.hasBlank(account, password)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if (account.length() < 4 || password.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号或密码过短");
        }
        // 2.加密
        String encryptPassword = getEncryptPassword(password);
        // 3.查询数据库中是否存在该用户，不存在则抛异常
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("account", account).eq("password", encryptPassword);
        User user = this.baseMapper.selectOne(userQueryWrapper);
        if (user == null) {
            log.error("user login failed, account cannot match password");
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在或密码错误");
        }
        // 4.保存用户登录态
        request.getSession().setAttribute(UserConstant.USER_LOGIN_STATE, user);

        return this.getLoginUserVO(user);
    }

    @Override
    public LoginUserVo getLoginUserVO(User user) {
        if (user == null) {
            return null;
        }
        LoginUserVo userVo = new LoginUserVo();
        BeanUtils.copyProperties(user, userVo);
        return userVo;
    }

    @Override
    public Boolean userLogout(HttpServletRequest request) {
        // 判断是否已经登陆
        if (request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE) == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        // 移除登录态
        request.getSession().removeAttribute(UserConstant.USER_LOGIN_STATE);
        return true;
    }

    @Override
    public User getLoginUser(HttpServletRequest request) {
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);
        User user = (User) userObj;
        if (user == null || user.getId() == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN_ERROR);
        }
        return user;
    }
}
